const path = require('path')
const mkdirp = require('mkdirp')
const multer = require('multer')
const util = require('../utils/index.js')

const storage = multer.diskStorage({
  destination: async function (req, file, cb) {
    const date = new Date()
    const year = date.getFullYear().toString()
    const month = (date.getMonth() + 1).toString()
    const day = date.getDay().toString()
    const dir = path.join('./uploads', year, month, day)
    await mkdirp(dir)
    cb(null, dir)
  },
  filename: function (req, file, cb) {
    const extName = path.extname(file.originalname)
    const uniqueSuffix = Date.now() + '-' + util.randNum(0, 1e9)
    cb(null, file.fieldname + '-' + uniqueSuffix + extName)
  }
})
const upload = multer({ storage: storage })

module.exports = upload
